package system_storage_service

import (
	"io"

	"gitee.com/Luna-CY/Golang-Project-Template/internal/context"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/errors"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/logger"
	"gitee.com/Luna-CY/Golang-Project-Template/model"
)

func (cls *Storage) DownloadObject(ctx context.Context, object *model.SystemObject) (io.ReadCloser, errors.Error) {
	if nil == object {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("ISS_GE.S_GE.DO_CT.142949 object is nil")

		return nil, errors.ErrorServerInternalError("ISS_GE.S_GE.DO_CT.165315", "异常的传入参数")
	}

	if model.SystemObjectStatusUploading == *object.Status {
		return nil, errors.New(errors.ErrorTypeInvalidRequest, "ISS_GE.S_GE.DO_CT.205514", "对象上传中，无法下载")
	}

	if model.SystemObjectStatusFailed == *object.Status {
		return nil, errors.New(errors.ErrorTypeInvalidRequest, "ISS_GE.S_GE.DO_CT.245531", "对象上传失败，无法下载")
	}

	if model.SystemObjectStatusDeleted == *object.Status {
		return nil, errors.New(errors.ErrorTypeInvalidRequest, "ISS_GE.S_GE.DO_CT.285540", "对象已删除，无法下载")
	}

	provider, err := cls.GetProviderByName(*object.Provider)
	if err != nil {
		return nil, err.Relation(errors.ErrorServerInternalError("ISS_GE.S_GE.DO_CT.325557", "获取存储提供商失败"))
	}

	reader, err := provider.GetObject(ctx, *object.Filepath)
	if err != nil {
		return nil, err.Relation(errors.ErrorServerInternalError("ISS_GE.S_GE.DO_CT.385736", "获取对象失败"))
	}

	return reader, nil
}
